<template>
  <div style="">
    <Header :left="true" leftText="返回" title="手工加严填报"> </Header>

    <van-form :style="autoHeight" @submit="onSubmit">
      <van-field class="formstyle" style="font-weight: bold" name="text" :value="item.valueplineid" label="生产线"
        placeholder="" />

      <van-field required style="font-weight: bold" readonly class="formstyle" :value="valueformstyle" name="picker"
        label="加严原因" placeholder="点击选择加严原因" @click="showPickerformstyle = true" />
      <van-popup v-model="showPickerformstyle" position="bottom">
        <van-picker show-toolbar :columns="columnsformstyle" @confirm="onConfirmformstyle"
          @cancel="showPickerformstyle = false">
          <template #option="option">
            <div style="display: flex; flex-direction: column; align-items: center">
              <div>{{ option.formstylename }}</div>
            </div>
          </template>
        </van-picker>
      </van-popup>

      <NoticeBar color="#1989fa" background="#ecf9ff" style="margin-top: 5px; font-size: 15px; font-weight: bold"
        left-icon="description">基本信息</NoticeBar>

      <van-field required style="font-weight: bold" readonly clickable class="formstyle" name="datetimePicker"
        :value="item.planworkdatetime" label="加严开始时间" placeholder="选择时间" @click="showPickerdatetime = true" />
      <van-popup v-model="showPickerdatetime" position="bottom">
        <van-datetime-picker type="datetime" @confirm="onConfirmdatetime" @cancel="showPickerdatetime = false"
          :min-date="minDate" :max-date="maxDate" :value="currentdate" />
      </van-popup>

      <van-field class="formstyle" style="font-weight: bold" name="picker" :value="showPOrderIDName(item.pOrderID)"
        label="生产订单" placeholder="" show-word-limit type="text" />

      <van-field class="formstyle" style="font-weight: bold" name="picker" :value="item.Id" label="外观检验记录" placeholder=""
        show-word-limit type="text" />


      <van-field style="font-weight: bold" v-model="item.message" class="formstyle" rows="4" autosize label="加严说明"
        type="textarea" maxlength="150" placeholder="输入加严说明" show-word-limit />


      <van-row class="button" gutter="2">
        <van-col span="12">
          <van-button color="#138087" round block type="primary" native-type="submit" @click="submitsure1">跳过</van-button>
        </van-col>
        <van-col span="12">
          <van-button color="#138087" round block type="info" native-type="submit" @click="submitsure">保存</van-button>
        </van-col>
      </van-row>

    </van-form>
  </div>
</template>
  
<script>
import {
  Col,
  Row,
  Form,
  Cell,
  Icon,
  Field,
  NumberKeyboard,
  Image as VanImage,
  Picker,
  popup,
  SubmitBar,
  Button,
  Loading,
  Overlay,
  Dialog,
  Toast,
  NoticeBar,
  Tag,
  DatetimePicker,
  ImagePreview,
  CellGroup,
  Uploader,
  Cascader,
  Calendar,
  RadioGroup,
  Radio,
  Divider,
  Stepper,
  AddressList,
  Checkbox,
  CheckboxGroup,
} from "vant";

import "vue-easytable/libs/themes-base/index.css";
import { VTable } from "vue-easytable";
import { _httpClient as _httpClientApisie } from "@/libs/apisie";
import { _httpClient as _httpClientApi } from "@/libs/api";
import { getToken, getBaseApiFrefix } from "@/libs/auth";
import Header from "@/components/header.vue";
import { storage } from "@/libs/utils";
import Tightcloseitem01 from "../tightenup/tightcloseitem01.vue";

Vue.use(Form);
Vue.use(Field);
Vue.use(Overlay);
Vue.use(Loading);
Vue.use(Picker);
Vue.use(popup);
Vue.use(SubmitBar);
Vue.use(VanImage);
Vue.use(DatetimePicker);
Vue.use(Cascader);
Vue.use(Calendar);
Vue.use(Cell);
Vue.use(RadioGroup);
Vue.use(Radio);
Vue.use(Divider);
Vue.use(Stepper);
Vue.use(Button);
Vue.use(AddressList);
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
Vue.use(Col);
Vue.use(Row);

export default {
  name: "qCcheckApplicationTightfill",
  components: {
    Form,
    Row,
    Col,
    Button,
    Header,
    Form,
    Cell,
    Icon,
    Field,
    NumberKeyboard,
    Dialog,
    Toast,
    NoticeBar,
    Row,
    Tag,
    popup,
    DatetimePicker,
    ImagePreview,
    CellGroup,
    Uploader,
    Col,
    Calendar,
    Cascader,
    Picker,
    RadioGroup,
    Radio,
    Divider,
    Stepper,
    VTable,
    AddressList,
    Checkbox,
    CheckboxGroup,
  },
  data() {
    return {
      showPickerPOrderID: false,
      valuepPOrderID: "123",
      columnsPOrderID: [],
      valueplineid: "123",
      itemsOne1: "",
      valueformstyleid: "",
      user: [],
      planworkdatetime: "",
      pOrderID: "",
      message: "",
      minDate: new Date(2023, 1, 1),
      maxDate: new Date(2025, 10, 1),
      currentdate: new Date(),
      nowDate: null,
      nowtimer: "",
      valuepline: "",
      showPickerpline: false,
      showPickerdatetime: false,
      form: {},
      item: {},
      columnspline: [],
      columnsPLineID: [],
      valueformstyle: "",
      showPickerformstyle: false,
      columnsABCType: [
        { ABCType: "1", ABCTypeName: "甲" },
        { ABCType: "2", ABCTypeName: "乙" },
        { ABCType: "3", ABCTypeName: "丙" },
        { ABCType: "4", ABCTypeName: "-未确定" },
      ],
      columnsformstyle: [
        { formstyleid: "SM03", formstylename: "质量异常加严" },
        { formstyleid: "SM04", formstylename: "生产条件异常加严" },
        { formstyleid: "SM02", formstylename: "机器设备异常加严" },
        { formstyleid: "SM01", formstylename: "关键工艺参数异常加严" },
      ],
      fromData: {},
      showButton: false,
      item2: {},
      item3: [],
      item4: ""
    };
  },
  created: function () {
    this.user = JSON.parse(storage.get("user"));
    this.user.userId = this.user.userName;
    api.requestPermission(
      {
        list: ["camera", "microphone", "storage"],
      },
      function (ret, err) { }
    );

    // try {
    //   var manageStorage = api.require('manageStorage');
    //   manageStorage.requestAllFilePermission({
    //   }, function (ret) {
    //     // api.alert({
    //     //   msg: JSON.stringify(ret)
    //     // })
    //   });
    // } catch {

    // }
    
    // this.getPline();
    // this.getPOrderID();
    this.item.planworkdatetime = this.getNowTime();
    this.bodyitems = api.pageParam.item;
    // alert(JSON.stringify( api.pageParam.item));
    // alert(JSON.stringify( api.pageParam.item.PLineID));
    // alert(JSON.stringify( api.pageParam.item.POrderID));
    this.item.valueformstyleid = this.columnsformstyle[0].formstyleid;
    this.valueformstyle = this.columnsformstyle[0].formstylename;
    // alert(this.columnsformstyle[2].formstyleid);
    // alert(this.columnsformstyle[2].formstylename);
    if (typeof api.pageParam.item != "undefined") {
      this.item = api.pageParam.item;
      this.item.planworkdatetime = this.getNowTime();
    }

    if (typeof api.pageParam.item2 != "undefined") {
      this.item2 = api.pageParam.item;
    }
    if (typeof api.pageParam.item3 != "undefined") {
      this.item3 = api.pageParam.item3;
    }


    this.item.valueplineid = String(api.pageParam.item.PLineID);
    this.item.pOrderID = String(api.pageParam.item.POrderID);

    // api.openWin({
    //   name: "quality-qCcheckApplicationNew",
    //   url: "./quality-qCcheckApplicationNew.html",
    //   reload: true,
    //   pageParam: {
    //     item: this.item,
    //     item2: this.item2,
    //     item3: this.item3,
    //   },
    // });
  },
  mounted() { },

  methods: {
    getNowTimeplus() {
      let dateTime
      let yy = new Date().getFullYear()
      let mm = new Date().getMonth() + 1
      let dd = new Date().getDate()
      let hh = new Date().getHours()
      let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes()
        :
        new Date().getMinutes()
      let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds()
        :
        new Date().getSeconds()
      dateTime = yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss
      return dateTime
    },
    async sendmessage(id) {
      try {
        // alert(id);
        let _this = this;

        let eventDescription = "";
        let eventDatetime = _this.getNowTimeplus();
        let eventTypeID = "N3";
        let eventID = "";
        let messageContent = "";
        let msgContentTypeID = "";
        let pLineID = "";
        let machineID = "";
        let pShiftID = "";
        let teamID = "";
        let pOrderID = "";
        let productionBarcode = "";
        let materialBarcode = "";
        let relatedEmployee = "";
        let messageStatus = "";
        let processBatchID = "";
        let beginDatetime = _this.getNowTimeplus();
        let sendFinished = false;
        let closed = false;

        msgContentTypeID = "ADS01";
        eventID = "ADS01";
        eventDescription = "加严管控记录:" + id + "已创建，请品管主任尽快判定等级！";
        messageContent = "加严管控记录:" + id + "已创建，请品管主任尽快判定等级！";


        let bodysss = {
          eventDescription: eventDescription,
          eventDatetime: eventDatetime,
          eventTypeID: eventTypeID,
          eventID: eventID,
          messageContent: messageContent,
          msgContentTypeID: msgContentTypeID,
          factoryID: "TC00",
          pLineID: pLineID,
          machineID: machineID,
          pShiftID: pShiftID,
          teamID: teamID,
          pOrderID: pOrderID,
          productionBarcode: productionBarcode,
          materialBarcode: materialBarcode,
          relatedEmployee: relatedEmployee,
          messageStatus: messageStatus,
          processBatchID: processBatchID,
          beginDatetime: beginDatetime,
          sendFinished: sendFinished,
          closed: closed
        };

        //alert(bodysss);
        try {
          let res = await _httpClientApisie.post(
            _httpClientApisie.getApiPrefix() + "/RealtimeEventMessage/SaveEntity",
            {
              body: bodysss
            }
          );
          //alert(JSON.stringify(res));
          if (res.Message == null) {
            Toast.clear();
            Toast.success("发送成功");


            api.openWin({
              name: "quality-qCcheckApplicationNew",
              url: "./quality-qCcheckApplicationNew.html",
              reload: true,
              pageParam: {
                item: _this.item,
                item2: _this.item2,
              },
            });
            setTimeout(function () {
              _this.$ac.closeWin();
            }, 2000);

          } else {
            Toast.clear();
            Toast.fail("发送失败");
          }
        } catch (e) {
          Toast.fail(JSON.stringify(e));
        }
      } catch (error) {
        alert(error);
      }

    },
    // 获取当前时间
    getNowTime() {
      let dateTime;
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth() + 1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf =
        new Date().getMinutes() < 10
          ? "0" + new Date().getMinutes()
          : new Date().getMinutes();
      let ss =
        new Date().getSeconds() < 10
          ? "0" + new Date().getSeconds()
          : new Date().getSeconds();
      dateTime = yy + "-" + mm + "-" + dd + " " + hh + ":" + ss;
      return dateTime;
    },
    onConfirmPOrderID(value, index) {
      this.item.valuepPOrderID =
        this.columnsPOrderID[index].POrderIDAndMaterialName;
      this.item.pOrderID = this.columnsPOrderID[index].POrderID;
      this.showPickerPOrderID = false;
    },
    //打开扫描
    showScanner() {
      let _this = this;
      if (
        api.deviceName.toLowerCase() == "huawei" ||
        api.deviceName.toLowerCase() == "honor"
      ) {
        // var QRScan = api.require("QRScan");
        // QRScan.customizedScanner(
        //   {
        //     rect: {
        //       x: 0, //（可选项）数字类型；模块左上角的 x 坐标（相对于所属的 Window 或 Frame）；默认：0
        //       y: 0, //（可选项）数字类型；模块左上角的 y 坐标（相对于所属的 Window 或 Frame）；默认：0
        //       w: 320, //（可选项）数字类型；模块的宽度；支持设置'auto'；默认：所属的 Window 或 Frame 的宽度
        //       h: 480, //（可选项）数字类型；模块的高度；支持设置'auto'；默认：所属的 Window 或 Frame 的高度
        //     },
        //     rectOfInterest: {
        //       x: 64, //（可选项）数字类型；扫码识别区域左上角的 x 坐标（相对于扫码区rect）；默认：0
        //       y: 65, //（可选项）数字类型；扫码识别区域左上角的 y 坐标（相对于扫码区rect）；默认：0
        //       w: 250, //（可选项）数字类型；扫码识别区域的宽度；默认：扫码区rect的宽度
        //       h: 250, //（可选项）数字类型；扫码识别区域的高度；默认：扫码区rect的高度
        //     },
        //     //tipString:'放入框内扫码',
        //     maskColor: "rgba(0,0,0,0.5)",
        //     scanLine: {
        //       color: "#00FF00",
        //       thickness: 2,
        //     },
        //     marginB: 30,
        //     formatType: "ALL",
        //   },
        //   function (ret) {
        //     if (ret) {
        //       alert(ret.content);
        //     }
        //   }
        // );
        //QRScan.closeCustomizedScanner();

        var zyHmsScan = api.require('zyHmsScan');
        var param = {
          //returnAll:true
        };
        zyHmsScan.openDefaultView(param, function (ret) {
          //_this.addBarCode(ret.result);

          let pattern = /[a-zA-Z]/;
          var b = pattern.test(ret.result);
          if (b) {
            //生产线代码
            _this.getValueplineidAndValuepline(ret.result);
          } else {
            //生产计划工单
            _this.item.pOrderID = ret.result;
            _this.item.valuepPOrderID = _this.showPOrderIDName(
              _this.item.pOrderID
            );
            _this.getMachineIDByPOrderIDFromMachineCurrentPOrder(
              ret.result
            );
          }


          //api.alert({ msg: JSON.stringify(ret) });
        });


      } else {
        var FNScanner = this.$ac.require("FNScanner");
        FNScanner.openScanner(
          {
            autorotation: true,
          },
          function (ret, err) {
            if (ret) {
              if (ret.eventType == "success" && ret.content != "") {
                let pattern = /[a-zA-Z]/;
                var b = pattern.test(ret.content);
                if (b) {
                  //生产线代码
                  _this.getValueplineidAndValuepline(ret.content);
                } else {
                  //生产计划工单
                  _this.item.pOrderID = ret.content;
                  _this.item.valuepPOrderID = _this.showPOrderIDName(
                    _this.item.pOrderID
                  );
                  _this.getMachineIDByPOrderIDFromMachineCurrentPOrder(
                    ret.content
                  );
                }
              }
            } else {
              //alert(JSON.stringify(err));
            }
          }
        );
      }
    },
    async getValueplineidAndValuepline(content) {
      // let _this = this;
      // _this.item.valueplineid = content;
      // _this.item.valuepline = _this.showPLineIDName(content);
      // _this.getPOrderIDByMachineIDFromMachineCurrentPOrder(content);
      // _this.$forceUpdate();
    },
    getNowTime() {
      let dateTime;
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth() + 1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf =
        new Date().getMinutes() < 10
          ? "0" + new Date().getMinutes()
          : new Date().getMinutes();
      let ss =
        new Date().getSeconds() < 10
          ? "0" + new Date().getSeconds()
          : new Date().getSeconds();
      dateTime = yy + "-" + mm + "-" + dd + " " + hh + ":" + mf + ":" + ss;
      return dateTime;
    },
    showABCTypeName(ABCType) {
      var ABCTypeName = ABCType;
      this.columnsABCType.forEach((item) => {
        if (item.ABCType === ABCType) {
          ABCTypeName = item.ABCTypeName;
        }
      });
      return ABCTypeName;
    },
    async getPOrderID() {
      let _this = this;
      try {
        let res = await _httpClientApisie.get(
          _httpClientApisie.getApiPrefix() + "/MachineCurrentPOrder/GetList"
        );
        if (res.HttpCode === "200") {
          let teamMap = res.Data.map((item) => ({
            POrderID: item.POrderID,
            MaterialName: item.MaterailName,
            MaterialID: item.MaterailID,
            POrderIDAndMaterialName: item.POrderID + " " + item.MaterailName,
          }));
          _this.columnsPOrderID = teamMap;
        }
      } catch (e) {
        //Toast.fail(JSON.stringify(e));
      }
    },
    showPOrderIDName(POrderID) {
      var POrderIDName = POrderID;
      this.columnsPOrderID.forEach((item) => {
        if (item.POrderID === POrderID) {
          POrderIDName = item.POrderIDAndMaterialName;
        }
      });
      return POrderIDName;
    },
    //获取生产线
    showPLineIDName(plineId) {
      var plineName = plineId;
      this.columnspline.forEach((item) => {
        if (item.plineId == plineId) {
          plineName = item.plineName;
        }
      });
      return plineName;
    },
    showFormstyle(formstyleid) {
      var formstylename = formstyleid;
      this.columnsformstyle.forEach((item) => {
        if (item.formstyleid === formstyleid) {
          formstylename = item.formstylename;
        }
      });
      return formstylename;
    },
    async confirmmessage(item) {
      let _this = this;
      //Toast.fail(JSON.parse(something))
      api.openWin({
        name: "qCcheckApplicationNew",
        url: "./tightenup-qCcheckApplicationNew.html",
        reload: true,
        pageParam: {
          item: item,
          form: {},
        },
      });
      setTimeout(function () {
        _this.$ac.closeWin();
      }, 1000);
    },
    async submitsure1() {
      // alert("oooooo====")
      let _this = this;
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "请稍等...",
      });


      Toast.success("跳过操作");
      api.openWin({
        name: "quality-qCcheckApplicationNew",
        url: "./quality-qCcheckApplicationNew.html",
        reload: true,
        pageParam: {
          item: _this.item,
          item2: _this.item2,
          item3: _this.item3,
        },
      });
      setTimeout(function () {
        _this.$ac.closeWin();
      }, 2000);
    },
    async submitsure() {
      // alert("oooooo")
      let _this = this;
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "请稍等...",
      });
      let bodyss = {
        factoryID: "TC00",
        abcType: "4",
        strictDescription: _this.item.message,
        required: "",
        memo: "",
        strictTypeID: "SM03",
        pLineID: _this.item.valueplineid,
        pOrderID: _this.item.pOrderID,
        fromDatetime: _this.item.planworkdatetime,
        creator: _this.user.userId,
        createDatetime: _this.getNowTime(),
      };
      //alert(JSON.stringify(bodyss));
      try {
        let res = await _httpClientApisie.post(
          _httpClientApisie.getApiPrefix() + "/AddStrictManage/SaveEntity",
          {
            body: bodyss,
          }
        );
        //alert(JSON.stringify(res));
        if (res.HttpCode == 200) {
          Toast.clear();
          Toast.success("保存成功");
          _this.sendmessage(res.Data);
          api.openWin({
            name: "quality-qCcheckApplicationNew",
            url: "./quality-qCcheckApplicationNew.html",
            reload: true,
            pageParam: {
              item: _this.item,
              item2: _this.item2,
              item3: _this.item3,
            },
          });
          setTimeout(function () {
            _this.$ac.closeWin();
          }, 2000);
          //alert(JSON.stringify(res))
        } else {
          Toast.clear();
          Toast.fail("保存失败");
          alert(JSON.stringify(res))
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    onConfirmdatetime(time) {
      this.tempTime = time;
      this.item.planworkdatetime = `${time.getFullYear()}-${time.getMonth() + 1
        }-${time.getDate()} ${time.getHours().toString().padStart(2, 0)}:${time
          .getMinutes()
          .toString()
          .padStart(2, 0)}`;
      this.showPickerdatetime = false;
    },
    onConfirmpline(value, index) {
      // this.item.valuepline = value;
      // this.item.valueplineid = this.columnspline[index].plineId;
      // this.item.valuepline = this.columnspline[index].plineName;
      // this.showPickerpline = false;
    },
    onConfirmformstyle(value, index) {
      this.valueformstyle = value;
      this.item.valueformstyleid = this.columnsformstyle[index].formstyleid;
      this.valueformstyle = this.columnsformstyle[index].formstylename;
      //alert(this.columnsformstyle[index].formstyleName);
      this.showPickerformstyle = false;
    },
    clear() {
      this.message = "";
      this.pOrderID = "";
    },
    async getPline() {
      let _this = this;
      try {
        let res = await _httpClientApisie.get(
          _httpClientApisie.getApiPrefix() +
          "/PLineEquipment/GetList?FactoryID=TC00"
        );
        if (res.HttpCode === "200") {
          //alert(JSON.stringify(res));
          let teamMap = res.Data.map((item) => ({
            plineId: item.PLineID,
            plineName: item.PLineName,
          }));
          _this.columnspline = teamMap;
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    async getMachineIDByPOrderIDFromMachineCurrentPOrder(POrderID) {
      let _this = this;
      try {
        let res = await _httpClientApisie.get(
          _httpClientApisie.getApiPrefix() +
          "/MachineCurrentPOrder/GetList?POrderID=" +
          POrderID
        );
        if (res.HttpCode === "200") {
          let teamMap = res.Data.map((item) => ({
            plineId: item.MachineID,
            plineName: _this.showPLineIDName(item.MachineID),
          }));
          _this.columnspline = teamMap;
          this.$forceUpdate();
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    async getPOrderIDByMachineIDFromMachineCurrentPOrder(MachineID) {
      let _this = this;
      try {
        let res = await _httpClientApisie.get(
          _httpClientApisie.getApiPrefix() +
          "/MachineCurrentPOrder/GetList?MachineID=" +
          MachineID
        );
        if (res.HttpCode === "200") {
          let teamMap = res.Data.map((item) => ({
            POrderID: item.POrderID,
            MaterialName: item.MaterailName,
            MaterialID: item.MaterailID,
            POrderIDAndMaterialName: item.POrderID + " " + item.MaterailName,
          }));
          _this.columnsPOrderID = teamMap;
          this.$forceUpdate();
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    async getOrderingInformation() {
      let _this = this;
      try {
        let res = await _httpClientApisie.get(
          _httpClientApisie.getApiPrefix() + "/ProductionOrder/GetList"
        );
        if (res.HttpCode === "200") {
          _this.itemsOne1 = res.Data;
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
  },
};
</script>
  
<style></style>
  